package edu.gatech.teamrocket;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.j256.ormlite.dao.Dao;

import edu.gatech.teamrocket.models.*;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

public class EditTaskActivity extends Activity implements OnClickListener, TextWatcher {
	DewApplication app;
	Auth auth;
	Dao<Task, Integer> taskDao;
	
	Task task;
	
	private EditText taskName;
	private EditText taskDesc;
	private ToggleButton dateEnabled;
	private Button taskDate;
	private Button taskTime;
	private EditText taskLocation;
	private CheckBox allDayCheck;
	private CheckBox weeklyCheck;
	private Button addButton;
	private Button cancelButton;
	private Spinner categorySpinner;
	
	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;
	Time dateTimeValue;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (DewApplication) getApplicationContext();
		auth = app.getAuth();
		setContentView(R.layout.newtask);
		
		try {
			DatabaseHelper db = app.getHelper();
			Dao<Category, Integer> categoryDao = db.getCategoryDao();
			List<Category> categories = categoryDao.queryBuilder().where().eq("user_id", auth.getUser()).query();
			
			// get all the form elements
			taskName = (EditText) findViewById(R.id.taskName);
			taskDesc = (EditText) findViewById(R.id.taskDesc);
			dateEnabled = (ToggleButton) findViewById(R.id.dateEnabled);
			taskDate = (Button) findViewById(R.id.dateButton);
			taskTime = (Button) findViewById(R.id.timeButton);
			taskLocation = (EditText) findViewById(R.id.taskLocation);
			categorySpinner = (Spinner) findViewById(R.id.categorySpinner);
			addButton = (Button) findViewById(R.id.addButton);
			allDayCheck = (CheckBox) findViewById(R.id.allDayCheckBox);
			weeklyCheck = (CheckBox) findViewById(R.id.weeklyCheckBox);
			cancelButton = (Button) findViewById(R.id.cancelButton);
			
			Bundle extras = getIntent().getExtras();
			int taskID = extras.getInt("TASK_ID");
			
			try {
				taskDao = app.getHelper().getTaskDao();
				task = taskDao.queryForId(taskID);
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
			
			dateTimeValue = new Time();
			
			taskName.setText(task.getName());
			taskDesc.setText(task.getDetails());
			if (task.getTime() == null) {
				dateTimeValue.setToNow();
				dateTimeValue.second = 0;
				dateTimeValue.minute = 0;
				dateTimeValue.hour = 0;
				dateTimeValue.allDay = true;
				dateEnabled.setChecked(false);
				allDayCheck.setChecked(true);
				taskTime.setVisibility(View.GONE);
			} else {
				dateTimeValue.set(task.getTime().getTime());
				dateEnabled.setChecked(true);
				if (dateTimeValue.second == 0 && dateTimeValue.minute == 0 && dateTimeValue.hour == 0) {
					allDayCheck.setChecked(true);
					taskTime.setVisibility(View.GONE);
				}
				weeklyCheck.setChecked(task.getRecurring());
			}
			
			updateDateTime();
			
			
			// create an adapter for the category spinner
			final ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this, android.R.layout.simple_spinner_item, categories);
			
			// set the category spinner's adapter to the one we just made
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            categorySpinner.setAdapter(adapter); 
			
			addButton.setOnClickListener(this);
			taskDate.setOnClickListener(this);
			taskTime.setOnClickListener(this);
			cancelButton.setOnClickListener(this);
			taskName.addTextChangedListener(this);
			taskDesc.addTextChangedListener(this);
			allDayCheck.setOnClickListener(this);
			
			addButton.setText("Save Task");
			((TextView) findViewById(R.id.newTaskTitle)).setText("Edit Task");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Edits the date/time button text.
	 */
	public void updateDateTime() {
		long dtDob = dateTimeValue.toMillis(true);
        CharSequence str1 = DateFormat.format("MMMM d, yyyy", dtDob);
        CharSequence str2 = DateFormat.format("h:mmAA", dtDob);
        taskDate.setText(str1);
        taskTime.setText(str2);
	}
	
	/**
	 * DatePicker/TimePicker dialogs for Task's date.
	 */
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mDateSetListener,
	                    dateTimeValue.year, dateTimeValue.month, dateTimeValue.monthDay);
	    case TIME_DIALOG_ID:
	    	return new TimePickerDialog(this, mTimeSetListener, dateTimeValue.hour, dateTimeValue.minute, false);
	    }
	    return null;
	}
	
	/**
	 * DatePicker listener.
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener =
			new DatePickerDialog.OnDateSetListener() {
				public void onDateSet(DatePicker view, int year, int monthOfYear,
						int dayOfMonth) {
                    dateTimeValue.monthDay = dayOfMonth;
                    dateTimeValue.month = monthOfYear;
                    dateTimeValue.year = year;
                    updateDateTime();
				}
    };
    
	/**
	 * TimePicker listener.
	 */
	private TimePickerDialog.OnTimeSetListener mTimeSetListener =
			new TimePickerDialog.OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hour, int minute) {
					dateTimeValue.hour = hour;
					dateTimeValue.minute = minute;
					updateDateTime();
				}
    };
	
	@Override
	public void onClick(View v) {
		Intent i;
		switch (v.getId()) {
		case R.id.cancelButton: // has the cancel button been pressed?
			Toast.makeText(this, "Maybe another time!", Toast.LENGTH_LONG).show();
			i = new Intent(getApplicationContext(), ListActivity.class);
			startActivity(i);	
			break;
		case R.id.dateButton:
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.timeButton:
			showDialog(TIME_DIALOG_ID);
			break;
		case R.id.allDayCheckBox:
			if (allDayCheck.isChecked()) {
				taskTime.setVisibility(View.GONE);
				dateTimeValue.hour = 0;
				dateTimeValue.minute = 0;
				dateTimeValue.allDay = true;
			} else {
				taskTime.setVisibility(View.VISIBLE);
				dateTimeValue.allDay = false;
			}
			updateDateTime();
			break;
		case R.id.addButton:		
			String name = taskName.getText().toString();
			String details = taskDesc.getText().toString();
			String location = taskLocation.getText().toString();
			boolean weekly = weeklyCheck.isChecked();
			
			Category selectedCategory = (Category) categorySpinner.getSelectedItem(); // get the selected category
			
			task.setId(task.getId());
			task.setUser(auth.getUser());
			task.setName(name);
			task.setCategory(selectedCategory);
			if (details.length() > 0) {
				task.setDetails(details);
			}
			if (location.length() > 0) {
				task.setLocation(location);
			}
			task.setRecurring(false);
			if (dateEnabled.isChecked()) { // if the date is enabled, set the task's time
				task.setTime(new Date(dateTimeValue.toMillis(true)));
				task.setRecurring(weekly);
			} else {
				task.setTime(null);
				task.setRecurring(false);
			}
			
			// add the task to the database
			try {
				DatabaseHelper db = app.getHelper();
				Dao<Task, Integer> taskDao = db.getTaskDao();
				taskDao.update(task);
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
	
			Toast.makeText(this, "The task was edited successfully!", Toast.LENGTH_LONG).show();
			
			i = new Intent(getApplicationContext(), ListActivity.class);
			i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // remove this activity from history
    		startActivity(i);
    		finish();
    		break;
		}
	}
	
	@Override
	public void afterTextChanged(Editable s) {
		String name = taskName.getText().toString();
		String details = taskDesc.getText().toString();
		
		if (name.length() > 0) { // is name filled in?
			addButton.setEnabled(true);
		} else {
			addButton.setEnabled(false);
		}
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) { }
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) { }
}